package com.atguigu.ssyx.sys.service.impl;


import com.atguigu.ssyx.common.exception.SsyxException;
import com.atguigu.ssyx.common.result.ResultCodeEnum;
import com.atguigu.ssyx.model.sys.RegionWare;
import com.atguigu.ssyx.sys.mapper.RegionWareMapper;
import com.atguigu.ssyx.sys.service.RegionWareService;
import com.atguigu.ssyx.vo.sys.RegionWareQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 城市仓库关联表 服务实现类
 * </p>
 *
 * @author lqh
 * @since 2023-09-25
 */
@Service
public class RegionWareServiceImpl extends ServiceImpl<RegionWareMapper, RegionWare> implements RegionWareService {

    //开通区域列表查询
    @Override
    public IPage<RegionWare> selectPageReginWare(Page<RegionWare> warePage, RegionWareQueryVo regionWareQueryVo) {

        //1.获取查询条件值
        String keyword = regionWareQueryVo.getKeyword();

        //2.判断是否为空
        LambdaQueryWrapper<RegionWare> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)) {
            //条件封装
            //根据区域名称 或者仓库名称查询
            queryWrapper.like(RegionWare::getRegionName, keyword)
                    //or方法 表示并列 或者的关系 要么根据RegionName 要么WareName查
                    .or().like(RegionWare::getWareName, keyword);
        }
        //3.实现分页查询
        IPage<RegionWare> regionWareIPage = baseMapper.selectPage(warePage, queryWrapper);
        return regionWareIPage;
    }

    @Override
    public void saveRegionWare(RegionWare regionWare) {
        //判断区域是否已经开通了
        LambdaQueryWrapper<RegionWare> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(RegionWare::getRegionId, regionWare.getRegionId());
        //返回值大于0 说明有这个数据
        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            //已经存在 手动抛出自定义异常
            throw new SsyxException(ResultCodeEnum.REGION_NO_OPEN);
        }
        //添加
        baseMapper.insert(regionWare);
    }

    //取消开通区域
    @Override
    public void updateStatus(Long id, Integer status) {
        RegionWare regionWare = baseMapper.selectById(id);
        regionWare.setStatus(status);
        baseMapper.updateById(regionWare);
    }
}
